﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using MedicalManagementSystem.Models;
using MedicalManagementSystem.Utils;
using Menu = MedicalManagementSystem.Utils.Menu;
using MedicalManagementSystem.Helpers;

namespace MedicalManagementSystem.Controllers
{
    public class PatientController : GenericController
    {
        //
        // GET: /Patient/

        public ActionResult Index()
        {
            Menu.ID = "patient,active";
            var paginatedList = new PaginatedList<Patient>(Patient.SortPatients(Patient.CurrentPatients), 0);
            return View(new PatientTableModel("Текущие пациенты", Url.Action("FindFromActivePatients"), paginatedList));
        }

        //
        // GET: /Patient/Details/5
        
        public ActionResult Details(int id)
        {
            var patient = Patient.GetByPK(id);
            patient.Load();
            return View(patient);
        }

        //
        // GET: /Patient/Create
        [EnumAuthorize(Roles = UserRoles.DoctorRole 
                             | UserRoles.RegistratorRole )]
        public ActionResult Create()
        {
            Menu.ID = "patient,add";
            return View();
        }

        //
        // POST: /Patient/Create

        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole )]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            var patient = new Patient();
            try
            {
                UpdateModel(patient);
                DbContext.Instance.AddToPatient(patient);
                DbContext.Instance.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ClearModelStateErrors();
                AddViolataionsToModelState(patient.GetRuleViolations());
            }
            return View();
        }

        public JsonResult Validate(string propertyName, string propertyValue)
        {
            bool result = false;
            var jsonList = new List<string>();
            if (propertyName == "Surname")
            {
                var patients = DbContext.Instance.Patient.Where(p => p.Surname == propertyValue).ToList();
                result = patients.Count() == 0;
                jsonList = patients.Select(p => p.ToString()).ToList();

            }
            return Json(new { success = result, data = jsonList });
        }

        //
        // GET: /Patient/Edit/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole )]
        public ActionResult Edit(int id)
        {
            return View(Patient.GetByPK(id));
        }

        //
        // POST: /Patient/Edit/5

        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole )]
        [HttpPost]
        public ActionResult Edit(Patient patient)
        {
            var original = Patient.GetByPK(patient.id);
            try
            {
                // TODO: Add update logic here)
                DbContext.Instance.Patient.ApplyCurrentValues(patient);
                DbContext.Instance.SaveChanges();
                return RedirectToAction("Details", new { original.id });
            }
            catch (RuleViolationException)
            {
                ClearModelStateErrors();
                AddViolataionsToModelState(original.GetRuleViolations());
            }
            return View(original);
        }

        //
        // GET: /Patient/Delete/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole )]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Patient/Delete/5

        [HttpPost]
        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole )]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        [EnumAuthorize(Roles = UserRoles.DoctorRole
                             | UserRoles.RegistratorRole | UserRoles.ArchiverRole)]
        [HttpGet]
        public ActionResult Archive()
        {
            Menu.ID = "patient,archive";
            return View("Index", new PatientTableModel("Архив", Url.Action("FindFromAllPatients"),
                new PaginatedList<Patient>(Patient.SortedPatients)));
        }

        #region Patient Ajax Table

        public JsonResult FindFromPassivePatients(string searchPattern, int maxRows)
        {
            var patients = Patient.SearchPatient(searchPattern).ToArray()
                .Where(p => p.CurrentChart == null).Take(maxRows)
                .Select(p => new
                {
                    Id = p.id,
                    Initials = p.Initials,
                    Birthday = p.Birthday.ToShortDateString()
                });
            return Json(new { FindedPatients = patients.ToArray() });
        }

        public ActionResult FindFromAllPatients(int page, string searchPattern)
        {
            IEnumerable<Patient> patients = Patient.SearchPatient(searchPattern);
            var paginatedList = new PaginatedList<Patient>(patients, page);
            return View("PatientListControl", paginatedList);
        }

        public ActionResult FindFromActivePatients(int page, string searchPattern)
        {
            IEnumerable<Patient> patients = Patient.SearchPatient(Patient.CurrentPatients, searchPattern);
            var paginatedList = new PaginatedList<Patient>(patients, page);
            return View("PatientListControl", paginatedList);
        }

        #endregion
    }

}
